<template>
  <!-- Add this error display section before the main content -->
  <div v-if="initError" class="error-container">
    <div class="error-content">
      <div class="error-message">
        <el-icon class="error-icon">
          <Warning />
        </el-icon>
        <div class="error-text">
          <h3>数据加载失败</h3>
          <p>无法加载客户交易数据，请检查网络连接或稍后重试</p>
        </div>
      </div>
      <el-button type="primary" icon="Refresh" @click="retryInit" style="margin-top: 15px">
        重新加载
      </el-button>
    </div>
  </div>
  <div v-else class="metal-combine-container-wrapper" style="height: 100%; overflow: auto;">
    <div class="metal-combine-container" style="min-width: 800px;">
      <el-row style="border-bottom: 1px solid #dcdfe6;  padding:5px;">
        <el-col :span="24" style="padding-top: 8px; padding-left: 24px; padding-bottom: 4px; ">
          <span style="font-weight: bold;"> {{ targetObj?.name }} </span>
          <el-button style="margin-left: 20px;" icon="Refresh" @click="refreshList">刷新列表</el-button>

          <!-- Collapsible Menu Trigger -->
          <div style="float: right;">
            <el-tooltip :content="showCommoditySettings ? '收起设置' : '更多设置'" placement="top">
              <el-button :icon="showCommoditySettings ? 'ArrowUp' : 'ArrowDown'"
                @click="showCommoditySettings = !showCommoditySettings" circle>
              </el-button>
            </el-tooltip>
          </div>
          <div style="clear: both;"></div>
        </el-col>

        <!-- Collapsible Commodity Visibility Control -->
        <el-collapse-transition>
          <div>
            <div v-show="showCommoditySettings" style="padding: 0 24px; width: 100%;">
              <div
                style="border: 1px solid #dcdfe6; border-radius: 4px; margin-top: 5px; margin-bottom: 10px; padding: 15px;">
                <div style="display: flex; flex-wrap: wrap; gap: 20px; align-items: center;">
                  <span>商品列显示设置:</span>
                  <div v-for="commodity in metalCommodities" :key="commodity.id"
                    style="display: flex; align-items: center; gap: 8px;">
                    <span style="font-weight: 500;">{{ commodity.standard }}:</span>
                    <el-checkbox-group v-model="visibleSalesCommodities">
                      <el-checkbox :label="commodity.id">销售</el-checkbox>
                    </el-checkbox-group>
                    <el-checkbox-group v-model="visiblePurchaseCommodities">
                      <el-checkbox :label="commodity.id">回购</el-checkbox>
                    </el-checkbox-group>                   
                  </div>
                </div>
              </div>
            </div>
            <!-- Add new section for metal fund account visibility settings -->
            <div v-show="showCommoditySettings" style="padding: 0 24px; width: 100%;">
              <div
                style="border: 1px solid #dcdfe6; border-radius: 4px; margin-top: 5px; margin-bottom: 10px; padding: 15px;">
                <div style="display: flex; flex-wrap: wrap; gap: 20px; align-items: center;">
                  <span>收支列显示设置:</span>
                  <div v-for="commodity in metalCommodities" :key="commodity.id + '_fund'"
                    style="display: flex; align-items: center; gap: 8px;">
                    <span style="font-weight: 500;">{{ commodity.standard }}:</span>

                    <el-checkbox-group v-model="visibleMetalInFundAccounts">
                      <el-checkbox :label="commodity.metalAccountTypeId">来料</el-checkbox>
                    </el-checkbox-group>

                    <el-checkbox-group v-model="visibleMetalOutFundAccounts">
                      <el-checkbox :label="commodity.metalAccountTypeId">付料</el-checkbox>
                    </el-checkbox-group>

                  </div>
                </div>
              </div>
            </div>
            <div v-show="showCommoditySettings" style="padding: 0 24px; width: 100%;">
              <div
                style="border: 1px solid #dcdfe6; border-radius: 4px; margin-top: 5px; margin-bottom: 10px; padding: 15px;">
                <span> 结算记录:</span>
                <div v-for="peroid in periodRecords" :key="peroid.id"
                  style="display: flex; align-items: center; gap: 8px;">
                  <span style="font-weight: 500;">{{ peroid.name }}:</span>

                    <el-checkbox-group v-model="visibleSalesCommodities">
                      <el-checkbox :label="peroid.id">显示</el-checkbox>
                    </el-checkbox-group>

                </div>
              </div>
            </div>
          </div>
        </el-collapse-transition>
      </el-row>



      <!-- Rest of the template remains the same -->

      <el-row>
        <el-col :span="24" style="padding-top: 10px;" :style="{ minHeight: '400px', height: tableHeight }">
          <el-table v-loading="loading" :data="dataList" style="width: 100%; min-width: 600px; height: 100%;"
            @row-click="handleRowClick">


            <el-table-column label="业务日期" align="center" :width="fixedColumnWith">
              <template #default="scope">
                <el-date-picker v-if="!scope.row.isPeriodInitial" v-model="scope.row.operateDate" type="date"
                  placeholder="" :clearable="true" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="() => { }" />
              </template>
            </el-table-column>

            <el-table-column label="摘要" align="center" :width="fixedColumnWith">
              <template #default="scope">
                <input-cell :model-value="scope.row.title" :readonly="true" @update:modelValue="(value) => {

                }" />
              </template>
            </el-table-column>

            <!-- Metal Commodity Columns -->
            <template v-for="commodity in metalCommodities" :key="commodity.id">
              <!-- Sales Group -->
              <template v-if="visibleSalesCommodities.includes(commodity.id)">
                <el-table-column :label="'销售' + commodity.standard" align="center" :prop="'sales_' + commodity.id"
                  class-name="sales-group" :width="fixedColumnWith">
                  <template #default="scope">
                    <!-- Sales Quantity -->
                    <span v-for="batch in scope.row.salesCommodities" :key="batch.id">
                      <span v-if="batch.commodity?.id === commodity.id">
                        <input-cell :readonly="scope.row.isPeriodInitial" :model-value="batch.count.value"
                          :number-mode="true" :precision="countPrecision" @update:modelValue="(value) => {
                            batch.setCount(new CsDouble(value, countPrecision));
                            scope.row.calculatePriceAndQuantity(true);
                            customerTransitionMgr.calculateTotalData();
                          }" />
                      </span>
                    </span>
                  </template>
                </el-table-column>

                <el-table-column label="单价" align="center" :prop="'sales_price_' + commodity.id"
                  class-name="sales-group" :width="fixedColumnWith">
                  <template #default="scope">
                    <!-- Sales Price -->
                    <span v-for="batch in scope.row.salesCommodities" :key="batch.id">
                      <span v-if="batch.commodity?.id === commodity.id">
                        <input-cell :readonly="scope.row.isPeriodInitial" 
                        :model-value="batch.singlePriceAfterTax.value"
                          :number-mode="true" :precision="countPrecision" @update:modelValue="(value) => {
                            batch.setSinglePriceAfterTax(new CsFundDouble(value, fundPrecision));
                            scope.row.calculatePriceAndQuantity(true);
                            customerTransitionMgr.calculateTotalData();
                          }" />
                      </span>
                    </span>
                  </template>
                </el-table-column>

                <el-table-column label="应收货款" align="center" :prop="'sales_amount_' + commodity.id"
                  class-name="sales-group" :width="fixedColumnWith">
                  <template #default="scope">
                    <!-- Sales Amount -->
                    <span v-for="batch in scope.row.salesCommodities" :key="batch.id">
                      <span v-if="batch.commodity?.id === commodity.id">
                        <input-cell :readonly="scope.row.isPeriodInitial" :model-value="batch.batchPriceWithTax.value"
                          :number-mode="true" :precision="countPrecision" @update:modelValue="(value) => {
                            batch.setBatchPriceWithTax(new CsFundDouble(value, fundPrecision));
                            scope.row.calculatePriceAndQuantity(true);
                            customerTransitionMgr.calculateTotalData();
                          }" />
                      </span>
                    </span>
                  </template>
                </el-table-column>
              </template>

              <!-- Purchase Group -->
              <template v-if="visiblePurchaseCommodities.includes(commodity.id)">
                <el-table-column :label="'回购' + commodity.standard" align="center" :prop="'purchase_' + commodity.id"
                  class-name="purchase-group" :width="fixedColumnWith">
                  <template #default="scope">
                    <!-- Purchase Quantity -->
                    <span v-for="batch in scope.row.purchaseCommodities" :key="batch.id">
                      <span v-if="batch.commodity?.id === commodity.id">
                        <input-cell :readonly="scope.row.isPeriodInitial" :model-value="batch.count.value"
                          :number-mode="true" :precision="countPrecision" @update:modelValue="(value) => {
                            batch.setCount(new CsDouble(value, countPrecision));
                            scope.row.calculatePriceAndQuantity(true);
                            customerTransitionMgr.calculateTotalData();
                          }" />
                      </span>
                    </span>
                  </template>
                </el-table-column>

                <el-table-column label="单价" align="center" :prop="'purchase_price_' + commodity.id"
                  class-name="purchase-group" :width="fixedColumnWith">
                  <template #default="scope">
                    <!-- Purchase Price -->
                    <span v-for="batch in scope.row.purchaseCommodities" :key="batch.id">
                      <span v-if="batch.commodity?.id === commodity.id">
                        <input-cell :readonly="scope.row.isPeriodInitial" :model-value="batch.singlePriceAfterTax.value"
                          :number-mode="true" :precision="countPrecision" @update:modelValue="(value) => {
                            batch.setSinglePriceAfterTax(new CsFundDouble(value, fundPrecision));
                            scope.row.calculatePriceAndQuantity(true);
                            customerTransitionMgr.calculateTotalData();
                          }" />
                      </span>
                    </span>
                  </template>
                </el-table-column>

                <el-table-column label="应付金额" align="center" :prop="'purchase_amount_' + commodity.id"
                  class-name="purchase-group" :width="fixedColumnWith">
                  <template #default="scope">
                    <!-- Purchase Amount -->
                    <span v-for="batch in scope.row.purchaseCommodities" :key="batch.id">
                      <span v-if="batch.commodity?.id === commodity.id">
                        <input-cell :readonly="scope.row.isPeriodInitial" :model-value="batch.batchPriceWithTax.value"
                          :number-mode="true" :precision="countPrecision" @update:modelValue="(value) => {
                            batch.setBatchPriceWithTax(new CsFundDouble(value, fundPrecision));
                            scope.row.calculatePriceAndQuantity(true);
                            customerTransitionMgr.calculateTotalData();
                          }" />
                      </span>
                    </span>
                  </template>
                </el-table-column>
              </template>
            </template>

            <!-- Add this after your commodity columns and before 来款 column 
            <template v-for="fundAccountType in getAllMetalFundAccountTypes()" :key="fundAccountType.id">
              <el-table-column :label="fundAccountType.name" align="center" :width="fixedColumnWith">
                <template #default="scope">
                  <template v-for="fundAccount in getFundAccountForRow(scope.row, fundAccountType.id)"
                    :key="fundAccount.selfDefFundAccountType.id">
                    <input-cell :model-value="fundAccount.count.value" :number-mode="true" :precision="countPrecision"
                      @update:modelValue="(value) => {
                        fundAccount.count = new CsDouble(value, countPrecision);
                      }" />
                  </template>
                </template>
              </el-table-column>
            </template>
-->

            <!-- 贵金属收支 -->
            <template v-for="commodity in metalCommodities" :key="commodity.id + '_fund_group'">
              <!-- In Count Column (来料) -->
              <el-table-column v-if="visibleMetalInFundAccounts.includes(commodity.metalAccountTypeId)"
                :label="'来' + commodity.standard" align="center" :width="fixedColumnWith" class-name="metal-in-group">
                <template #default="scope">
                  <input-cell :readonly="scope.row.isPeriodInitial"
                    :model-value="getMetalInCount(scope.row, commodity.metalAccountTypeId)" :number-mode="true"
                    :precision="countPrecision" @update:modelValue="(value) => {
                      updateMetalInCount(scope.row, commodity.metalAccountTypeId, value);
                      customerTransitionMgr.calculateTotalData();
                    }" />
                </template>
              </el-table-column>

              <!-- Out Count Column (付料) -->
              <el-table-column v-if="visibleMetalOutFundAccounts.includes(commodity.metalAccountTypeId)"
                :label="'付' + commodity.standard" align="center" :width="fixedColumnWith" class-name="metal-out-group">
                <template #default="scope">
                  <input-cell :readonly="scope.row.isPeriodInitial"
                    :model-value="getMetalOutCount(scope.row, commodity.metalAccountTypeId)" :number-mode="true"
                    :precision="countPrecision" @update:modelValue="(value) => {
                      updateMetalOutCount(scope.row, commodity.metalAccountTypeId, value)
                      customerTransitionMgr.calculateTotalData();
                    }" />
                </template>
              </el-table-column>
            </template>


            <el-table-column label="来款" align="center" :width="fixedColumnWith">
              <template #default="scope">
                <input-cell :readonly="scope.row.isPeriodInitial" 
                :model-value="scope.row.receivedAmount?.value || 0"
                  :number-mode="true" :precision="fundPrecision" @update:modelValue="(value) => {
                    scope.row.receivedAmount = new CsFundDouble(value, fundPrecision);
                    customerTransitionMgr.calculateTotalData();
                  }" />
              </template>
            </el-table-column>

            <el-table-column label="已付款" align="center" :width="fixedColumnWith">
              <template #default="scope">
                <input-cell :readonly="scope.row.isPeriodInitial" 
                :model-value="scope.row.paymentAmount?.value || 0"
                  :number-mode="true" :precision="fundPrecision" @update:modelValue="(value) => {
                    scope.row.paymentAmount = new CsFundDouble(value, fundPrecision);
                    customerTransitionMgr.calculateTotalData();
                  }" />
              </template>
            </el-table-column>

            <!-- 贵金属存欠料 期初可以编辑，其他不可编辑 -->
            <template v-for="commodity in metalCommodities" :key="commodity.id + '_fund_group'">
              <!-- In Count Column (来料) -->
              <el-table-column v-if="visibleMetalInFundAccounts.includes(commodity.metalAccountTypeId)"
                :label="'存欠' + commodity.standard" align="center" :width="fixedColumnWith" class-name="metal-in-group">
                <template #default="scope">
                  <input-cell  :readonly="!scope.row.isPeriodInitial" 
                    :zero-as-blank="false"                
                    :model-value="getMetalBalance(scope.row, commodity.metalAccountTypeId)"
                    :number-mode="true" :precision="countPrecision"
                    @update:modelValue="(value) => {
                      updateMetalBalance(scope.row, commodity.metalAccountTypeId, value)
                      customerTransitionMgr.calculateTotalData();
                      }" />
                </template>
              </el-table-column>
            </template>
            <!-- 存欠款 -->
            <el-table-column label="存欠款" align="center" :width="fixedColumnWith">
              <template #default="scope">
                <input-cell :readonly="!scope.row.isPeriodInitial" 
                :zero-as-blank="false"  
                  :model-value="scope.row.balanceAfter?.value || 0" :number-mode="true"
                  :precision="fundPrecision" @update:modelValue="(value) => {
                    scope.row._balanceAfter = new CsFundDouble(value, fundPrecision);
                    customerTransitionMgr.calculateTotalData();
                  }" />
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" :width="fixedColumnWith">
              <template #default="scope">
                <input-cell :model-value="scope.row.remark" @update:modelValue="(value) => {
                }" />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <!-- Replace your current pagination section with this -->
      <div v-if="showPagination" style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { MetalUiAction } from '../../public/engine/uiAction/metalUiAction'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { CommonOrderStatus, OrderSortType } from '../../public/engine/common/docDefinition'
import { DataPage } from '../../public/network/communicationConverter'
import { MetalCombineOrder, MetalCombineOrderFilter } from '../../public/engine/metal/metalCombineOrder'
import { DateUtil } from '../../public/utils/dateUtil'
import EventBus from '../../public/engine/ipc/eventBus'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import { deleteMetalCombineOrderNetworkCache } from '../../public/network/api'
import { Util } from '../../public/utils/util'
import { Engine } from '../../public/engine/engine'
import { uiNavigation } from '../../public/views/uiEntrance/uiNavigation'
import { CommodityUiAction } from '../../public/engine/uiAction/commodityUiAction'
import { SubCommodityFilter, SubCommodityMetalFilterTypeEnum } from '../../public/engine/commodity/subCommodity'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'
import { Definition } from '../../public/engine/common/definition.js'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { CsDouble } from '../../public/engine/common/csDouble.js'
import { CustomerTransictionMgr } from '../../public/engine/metal/customerTransitionMgr'


export default {
  name: 'customerTransactionPage',

  components: {
    WarehouseSelect,
    InputCell,

  },

  props: {
    targetObj: {
      type: Object,
      default: null
    },
  },

  data() {
    return {
      CsFundDouble,
      CsDouble,
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 5,   // 1000 条显示，除了极端场景都能显示
      },
      filter: new MetalCombineOrderFilter(),
      dateRange: [],
      dataList: [],
      metalUiAction: new MetalUiAction(),
      inventoryUiAction: new InventoryUiAction(),
      CommonOrderStatus,
      OrderSortType,
      commodityUiAction: new CommodityUiAction(),
      metalCommodities: [],  // SubCommodity 贵金属商品列表
      visibleSalesCommodities: [],    // 控制销售组商品列的显示
      visiblePurchaseCommodities: [], // 控制回购组商品列的显示
      visibleMetalInFundAccounts: [],  // 控制贵金属来料账户列的显示
      visibleMetalOutFundAccounts: [], // 控制贵金属付料账户列的显示
      showCommoditySettings: false,   // 控制商品设置菜单的展开/收缩
      periodRecords: [
        { 'name': '2025年8月', 'id': 1 },
        { 'name': '2025年7月', 'id': 2 }
      ],
      customerTransitionMgr: null,
      initError: false,
    }
  },
  mounted() {
    if (!this.initData()) {
      // 初始化数据失败，显示错误信息页面

    }

    EventBus.on('metalCombineOrderUpdated', this.getList)
  },



  beforeUnmount() {
    EventBus.off('metalCombineOrderUpdated', this.getList)
  },

  computed: {

    fixedColumnWith() {
      return 120;
    },

    showPagination() {
      return this.total > this.queryParams.pageSize;
    },

    tableHeight() {
      // Dynamically calculate table height based on whether pagination is shown
      return this.showPagination ? 'calc(100vh - 220px)' : 'calc(100vh - 160px)';
    },

    fundPrecision() {
      return Definition.fundPrecision;
    },

    countPrecision() {
      return Definition.precision;
    },
  },

  methods: {

    // 初始化数据
    async initData() {
      this.initError = false; // Reset error state
      this.customerTransitionMgr = new CustomerTransictionMgr({
        commodityUiAction: this.commodityUiAction,
        metalUiAction: this.metalUiAction
      });

      this.initError = !await this.customerTransitionMgr.initData();
      this.metalCommodities = this.customerTransitionMgr.metalCommodities;
      this.dataList = this.customerTransitionMgr.orders;
      this.total = this.customerTransitionMgr.orders.length;

      // 插入空行
      this.customerTransitionMgr.fillEmptyLine();

      this.initDefaultCommodityGroups();
    },

    // Add this method to retry initialization
    async retryInit() {
      const success = await this.initData();
      if (!success) {
        ElMessage.error('重新加载失败，请稍后重试');
      } else {
        ElMessage.success('数据加载成功');
      }
    },

    /*
     默认商品group  显示逻辑
   1. 默认显示黄金销售和回收group, 黄金商品的standard 是 AU
   2. 根据getList 反馈的商品优化可显示的商品group:
       1) 如果商品为空，按默认商品group 显示
       2) 如果商品不为空，遍历商品，如果 商品的属性purchaseCommodities 中的商品 id 
         包含与 metalCommodities 中的一致，显示该商品回购group; 
         如果商品 salesCommodities 中的商品 id 包含与 metalCommodities 中的一致，
         显示该商品销售group
     */
    initDefaultCommodityGroups() {
      // 如果 metalCommodities 还没有加载完成，直接返回
      if (!this.metalCommodities || this.metalCommodities.length === 0) {
        return;
      }

      // 1. 默认显示黄金销售和回收group, 黄金商品的standard 是 AU
      const goldCommodity = this.metalCommodities.find(commodity => commodity.standard === 'AU');

      // 清空当前选择
      this.visibleSalesCommodities = [];
      this.visiblePurchaseCommodities = [];
      this.visibleMetalInFundAccounts = [];
      this.visibleMetalOutFundAccounts = [];

      if (goldCommodity) {
        // 默认显示黄金商品的销售和回购group
        // this.visibleSalesCommodities.push(goldCommodity.id);
        this.visiblePurchaseCommodities.push(goldCommodity.id);

        // 默认显示黄金商品的来料和付料group
        if (goldCommodity.metalAccountTypeId) {
          this.visibleMetalInFundAccounts.push(goldCommodity.metalAccountTypeId);
          //  this.visibleMetalOutFundAccounts.push(goldCommodity.metalAccountTypeId);
        }
      }

      // 2. 根据getList 反馈的商品优化可显示的商品group
      if (!this.dataList || this.dataList.length === 0) {
        // 2.1) 如果商品为空，按默认商品group 显示 (已经设置过了)
        return;
      }

      // 2.2) 如果商品不为空，遍历商品
      const salesCommodityIds = new Set();
      const purchaseCommodityIds = new Set();

      // 收集所有出现过的商品ID
      this.dataList.forEach(order => {
        // 检查销售商品
        if (order.salesCommodities && Array.isArray(order.salesCommodities)) {
          order.salesCommodities.forEach(salesItem => {
            if (salesItem.commodity && salesItem.commodity.id && salesItem.count.value > 0) {
              salesCommodityIds.add(salesItem.commodity.id);
            }
          });
        }

        // 检查回购商品
        if (order.purchaseCommodities && Array.isArray(order.purchaseCommodities)) {
          order.purchaseCommodities.forEach(purchaseItem => {
            if (purchaseItem.commodity && purchaseItem.commodity.id && purchaseItem.count.value > 0) {
              purchaseCommodityIds.add(purchaseItem.commodity.id);
            }
          });
        }
      });

      // 更新可见的商品group
      this.metalCommodities.forEach(commodity => {
        const commodityId = commodity.id;
        const metalAccountTypeId = commodity.metalAccountTypeId;

        // 如果该商品在销售商品中出现过，显示销售group
        if (salesCommodityIds.has(commodityId)) {
          if (!this.visibleSalesCommodities.includes(commodityId)) {
            this.visibleSalesCommodities.push(commodityId);

            // 如果该金属账户类型出现过，显示来料和付料group
            if (metalAccountTypeId) {
              if (!this.visibleMetalOutFundAccounts.includes(metalAccountTypeId)) {
                this.visibleMetalOutFundAccounts.push(metalAccountTypeId);
              }
            }
          }
        }

        // 如果该商品在回购商品中出现过，显示回购group
        if (purchaseCommodityIds.has(commodityId)) {
          if (!this.visiblePurchaseCommodities.includes(commodityId)) {
            this.visiblePurchaseCommodities.push(commodityId);

            if (metalAccountTypeId) {
              if (!this.visibleMetalInFundAccounts.includes(metalAccountTypeId)) {
                this.visibleMetalInFundAccounts.push(metalAccountTypeId);
              }
            }
          }
        }



      });
    },

    // 获取贵金属商品信息
    async getMetalCommodityInfo() {
      const res = await this.commodityUiAction.getCommoditySpecList(
        new DataPage(1, 0, 100),  // 大一些保障所有贵金属拿到     
        (new SubCommodityFilter({ metalType: SubCommodityMetalFilterTypeEnum.MetalSelfOnly })).toJson()
      )

      if (res?.data?.dataList) {
        this.metalCommodities = res.data.dataList;
        return null;
      }

      return "get metal commodity info failed"
    },
  
    ///////  贵金属收支列
    // Get metal fund account for a specific row and commodity
    getMetalFundAccount(row, metalAccountTypeId) {
      return row.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId);      
    },

    // Get in count (来料) for a metal fund account
    getMetalInCount(row, metalAccountTypeId) {
      const fundAccount = this.getMetalFundAccount(row, metalAccountTypeId);
      return fundAccount ? fundAccount.inCount.value : 0;
    },

    // Get out count (付料) for a metal fund account
    getMetalOutCount(row, metalAccountTypeId) {
      const fundAccount = this.getMetalFundAccount(row, metalAccountTypeId);
      return fundAccount ? fundAccount.outCount.value : 0;
    },

    // Update in count (来料) for a metal fund account
    updateMetalInCount(row, metalAccountTypeId, value) {
      const fundAccount = this.getMetalFundAccount(row, metalAccountTypeId);
      if (fundAccount) {
        fundAccount.inCount = new CsDouble(value, this.countPrecision);
      }
    },

    // Update out count (付料) for a metal fund account
    updateMetalOutCount(row, metalAccountTypeId, value) {
      const fundAccount = this.getMetalFundAccount(row, metalAccountTypeId);
      if (fundAccount) {
        fundAccount.outCount = new CsDouble(value, this.countPrecision);
      }
    },

    // 存欠料
    getMetalBalance(row, metalAccountTypeId) {
      const fundAccount = this.getMetalFundAccount(row, metalAccountTypeId);
      return fundAccount ? fundAccount.balanceAfter.value : 0;
    },

    // 更新存欠料
    updateMetalBalance(row, metalAccountTypeId, value) {
      const fundAccount = this.getMetalFundAccount(row, metalAccountTypeId);
      if (fundAccount) {
        fundAccount.balanceAfter = new CsDouble(value, this.countPrecision);
      }
    },

    ///////

    async getList() {
      let ret = null;
      try {
        this.loading = true;
        const result = await this.customerTransitionMgr.getList(
          this.queryParams.pageNum,
          this.queryParams.pageSize,
          this.dateRange
        );

        if (result && result.dataList) {
          this.dataList = result.dataList;
          this.total = Number(result.total) || 0;
          ret = result;
        } else {
          ElMessage.error('获取综合单据列表失败');
        }
      } catch (error) {
        console.error('获取综合单据列表失败', error);
        ElMessage.error('获取综合单据列表失败');
      } finally {
        this.loading = false;
        return ret;
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetSearch() {
      this.filter.clear()
      this.dateRange = []
      this.queryParams.pageNum = 1
      this.getList()
    },

    refreshList() {
      deleteMetalCombineOrderNetworkCache();
      this.getList()
    },

    createMetalCombineOrder() {
      // uiNavigation.showMetalCombineDetailPage(this.$router)
    },

    showDetail(row) {
      //  uiNavigation.showMetalCombineDetailPage(this.$router, { id: row.id })
    },

    handleRowClick(row) {
      this.showDetail(row)
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      return DateUtil.getDayTitle(dateStr)
    },

    formatCurrency(value) {
      return Util.getFundString(value)
    }
  }
}
</script>

<style scoped>
.metal-combine-container-wrapper {
  height: 100%;
  overflow: auto;
}

.metal-combine-container {
  min-width: 800px;
  /* Adjust based on your content needs */
  padding-top: 0px;
  padding-left: 0px;
}

:deep(.sales-group) {
  background-color: #f0f9ff !important;
}

:deep(.purchase-group) {
  background-color: #f0fdf4 !important;
}

:deep(.sales-group .cell),
:deep(.purchase-group .cell) {
  font-weight: 500;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
}

:deep(.metal-in-group) {
  background-color: #fff7e6 !important;
}

:deep(.metal-out-group) {
  background-color: #f9f0ff !important;
}

:deep(.metal-in-group .cell),
:deep(.metal-out-group .cell) {
  font-weight: 500;
}

/* Add styles for error  */
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 400px;
  background-color: #f5f5f5;
}

.error-content {
  text-align: center;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 500px;
}

.error-message {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.error-icon {
  font-size: 36px;
  color: #909399;
  margin-top: 5px;
}

.error-text h3 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 18px;
}

.error-text p {
  margin: 0;
  color: #909399;
  font-size: 14px;
  line-height: 1.5;
}
</style>